package com.example.myapplication2;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import com.example.myapplication2.db.TaskDao;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class TaskDetailActivity extends AppCompatActivity {
    private EditText etTitle, etDescription, etReminderDateTime;
    private ImageButton btnTimePicker;
    private AppCompatButton[] priorityButtons = new AppCompatButton[4];
    private int selectedPriority = -1;
    private String selectedDate = "", selectedTime = "";
    private TaskDao taskDao;
    private long currentUserId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_detail);

        taskDao = new TaskDao(this);
        
        // 获取当前用户ID
        SharedPreferences prefs = getSharedPreferences("user_info", MODE_PRIVATE);
        currentUserId = prefs.getLong("user_id", -1);
        
        if (currentUserId <= 0) {
            // 如果没有用户ID，返回登录页面
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        initViews();
        setupListeners();
    }

    private void initViews() {
        etTitle = findViewById(R.id.et_task_title);
        etDescription = findViewById(R.id.et_task_description);
        etReminderDateTime = findViewById(R.id.et_reminder_time);
        btnTimePicker = findViewById(R.id.btn_time_picker);

        // 初始化优先级按钮
        priorityButtons[0] = findViewById(R.id.btn_priority_1);
        priorityButtons[1] = findViewById(R.id.btn_priority_2);
        priorityButtons[2] = findViewById(R.id.btn_priority_3);
        priorityButtons[3] = findViewById(R.id.btn_priority_4);
    }

    private void setupListeners() {
        // 设置返回按钮监听
        findViewById(R.id.iv_back).setOnClickListener(v -> {
            String title = etTitle.getText().toString().trim();
            String description = etDescription.getText().toString().trim();
            
            // 如果标题不为空，则保存
            if (!title.isEmpty()) {
                taskDao.addTask(
                    title,
                    description,
                    selectedDate,
                    selectedTime,
                    selectedPriority,
                    currentUserId
                );
            }
            finish();
        });

        // 设置添加按钮监听
        findViewById(R.id.fab_add).setOnClickListener(v -> {
            String title = etTitle.getText().toString().trim();
            String description = etDescription.getText().toString().trim();
            
            if (!title.isEmpty()) {
                if (taskDao.addTask(
                        title,
                        description,
                        selectedDate,
                        selectedTime,
                        selectedPriority,
                        currentUserId)) {
                    Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                    clearInputs();
                } else {
                    Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "请输入任务标题", Toast.LENGTH_SHORT).show();
            }
        });

        // 日期时间选择监听
        etReminderDateTime.setOnClickListener(v -> {
            try {
                showDatePicker();
            } catch (Exception e) {
                Toast.makeText(this, "日期选择失败", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        });

        btnTimePicker.setOnClickListener(v -> {
            try {
                showTimePicker();
            } catch (Exception e) {
                Toast.makeText(this, "时间选择失败", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        });

        // 设置优先级按钮监听
        for (int i = 0; i < priorityButtons.length; i++) {
            final int priority = i;
            priorityButtons[i].setOnClickListener(v -> selectPriority(priority));
        }
    }

    private void showDatePicker() {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(
            this,
            (view, year, month, dayOfMonth) -> {
                selectedDate = String.format("%d年%02d月%02d日", year, month + 1, dayOfMonth);
                updateReminderDateTime();
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        );
        datePickerDialog.show();
    }

    private void showTimePicker() {
        Calendar calendar = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(
            this,
            (view, hourOfDay, minute) -> {
                selectedTime = String.format("%02d:%02d", hourOfDay, minute);
                updateReminderDateTime();
            },
            calendar.get(Calendar.HOUR_OF_DAY),
            calendar.get(Calendar.MINUTE),
            true
        );
        timePickerDialog.show();
    }

    private void updateReminderDateTime() {
        String dateTime = selectedDate;
        if (!selectedTime.isEmpty()) {
            dateTime += " " + selectedTime;
        }
        etReminderDateTime.setText(dateTime);
    }

    private void selectPriority(int priority) {
        // 重置所有按钮大小
        for (AppCompatButton button : priorityButtons) {
            button.animate().scaleX(1f).scaleY(1f).setDuration(200).start();
        }

        // 放大选中的按钮
        priorityButtons[priority].animate()
            .scaleX(1.1f)
            .scaleY(1.1f)
            .setDuration(200)
            .start();

        selectedPriority = priority;
    }

    private void clearInputs() {
        try {
            etTitle.setText("");
            etDescription.setText("");
            etReminderDateTime.setText("");
            selectedDate = "";
            selectedTime = "";
            
            // 重置优先级按钮
            for (AppCompatButton button : priorityButtons) {
                if (button != null) {  // 添加null检查
                    button.animate().scaleX(1f).scaleY(1f).setDuration(200).start();
                }
            }
            selectedPriority = -1;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} 